package com.nine.system.service.impl;

import com.nine.common.pojo.Permission;
import com.nine.system.dao.PermissionDao;
import com.nine.system.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: nine-education-parent
 * @author: ♥丁新华
 * @create: 2023-05-23 18:49
 **/
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public List<Permission> selectByUserID(String userId) {

        List<Permission> permissionList = permissionDao.selectByUserID (userId);
        //  先查询所有一级菜单
        List<Permission> firsts=new ArrayList<>();
        for(Permission permission:permissionList){
            if(permission.getPid().equals("1")){
                firsts.add(permission);
            }
        }
        //  再查询二级菜单
        for(Permission first:firsts){

            List<Permission> children = findChildren(first.getId(), permissionList);
            first.setChildren(children);
        }
        return firsts;
    }

    //  获取到下边 子菜单
    private List<Permission> findChildren(String pid, List<Permission> permissions){

        List<Permission> children=new ArrayList<>();
        for(Permission p:permissions){
            if(p.getPid().equals(pid)){
                children.add(p);
            }
        }
        for(Permission p:children){
            p.setChildren(findChildren(p.getId(),permissions));
        }
        return children;
    }

}

